/*********************************************************************************************************
*	Projeto Final: SCC-0143 - Programação Concorrente						
*	Professor: Julio Cezar Estrella
*	Integrantes: Cesar Augusto Sales Gomes
*		         Matheus Salgado Boscariol
*	             Robson Pereira ALeixo
*
*	Gerador de Palavras:
*		Gerar palavras com tamanhos até 5 caracteres e verificar se elas estão em um arquivo
*
*
**********************************************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "mpi.h"
#include "loadArchive.h"
#include "generateAndSurch.h"


int main(int argc, char **argv){

	int blocklengths[4];
	int i;
	/*Criando Estrutura em MPI, para que ela poça ser passada por mensagem*/
	MPI_Datatype mpi_wff;
	MPI_Aint tamText, tamhead, displacements[4];
	MPI_Datatype oldtypes[4];
	MPI_Status status;

	blocklengths[0] = tamArrayHead*qtdWordPorPos*sizeWord;
	blocklengths[1] = tamArrayHead;
	blocklengths[2] = tamArrayHead;
	blocklengths[3] = 1;
	MPI_Type_extent(MPI_CHAR, &tamText);
	MPI_Type_extent(MPI_INT, &tamhead);
	displacements[0] = 0;
	displacements[1] = tamArrayHead*qtdWordPorPos*sizeWord;
	displacements[2] = (tamArrayHead*qtdWordPorPos*sizeWord)+tamArrayHead;
	displacements[3] = (tamArrayHead*qtdWordPorPos*sizeWord)+tamArrayHead+tamArrayHead;
	oldtypes[0] = MPI_CHAR;
	oldtypes[1] = MPI_INT;
	oldtypes[2] = MPI_INT;
	oldtypes[3] = MPI_INT;
	MPI_Type_struct(4,blocklengths, displacements, oldtypes, &mpi_wff);
	MPI_Type_commit(&mpi_wff);
	
	int id, num_proc, tam_calc;
	

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &id); /*ID do processo*/
    MPI_Comm_size(MPI_COMM_WORLD, &num_proc); /*Quantidade de processos*/
    
    /*Nó Zero*/
    if(id == 0){
	
	int conPalavrasRecv;
	int contPalavras = 0;
    	WordFromFile WFF;

    	alocaWFF(&WFF);
    	loadFile(&WFF);

    	/*envia estrutra para todos os processos*/
    	MPI_Bcast(&WFF,1,mpi_wff,0,MPI_COMM_WORLD);

    	for(i = num_proc ; i>0 ; i--){
    		
    		MPI_Recv(&conPalavrasRecv,1,MPI_INT,i,0,MPI_COMM_WORLD,&status);
    		
    		contPalavras += conPalavrasRecv;
    	}

    	imprime(&WFF);
    	MPI_Finalize();
    /*Nó Raiz*/
    }if(id > 0){
	
	WordFromFile WFF;
    	MPI_Bcast(&WFF,1,mpi_wff,0,MPI_COMM_WORLD);

    	int ini,fim;
	tam_calc = (int)tamArrayHead/num_proc;
    	ini = (id-1)*tam_calc;
        
        if(id == num_proc-1)
            fim = tamArrayHead-1;
        else
            fim = (id*tam_calc)-1;

        WordGenerate WG;
	
		alocarWG(&WG);

    	findWordUntilFive(&WG, &WFF, ini,fim);
    	
    	MPI_Finalize();
    }
	
return 0;
}

